﻿using PagedList;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using treasure.NET;
using treasure.NET.Models;

namespace treasure.NET.Controllers
{
    public class WebsitesController : Controller
    {
        private TreasureEntities db = new TreasureEntities();

        // GET: Websites
        public ActionResult Index(int? page, string key = null)
        {
            ViewBag.key = key;
            int pageNumber = page ?? 1;
            ViewBag.OnePageOfWebsites = db.websites
                .Where(w => key == null || w.url.Contains(key) || w.title.Contains(key) || w.desc.Contains(key))
                .Include(w => w.category)
                .OrderByDescending(w => w.pageview).ToPagedList(pageNumber, 20);

            return View();
        }

        public bool Jump(int id)
        {
            var website = db.websites.FirstOrDefault(w => w.id == id);
            website.pageview += 1;
            var browse = new browse { createat = (int)DateTime.Now.Ticks, uid = null, websiteid = id };
            db.browses.Add(browse);
            db.SaveChanges();

            return true;
        }

        // GET: Websites/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            website website = db.websites.Find(id);
            if (website == null)
            {
                return HttpNotFound();
            }
            return View(website);
        }

        // GET: Websites/Create
        public ActionResult Create()
        {
            ViewBag.categoryid = new SelectList(db.categories, "id", "name");
            return View();
        }

        private long GetPHPTimeStamp()
        {
            DateTime timeStamp = new DateTime(1970, 1, 1);  //得到1970年的时间戳
            return (DateTime.Now.Ticks - timeStamp.Ticks) / 10000000 - 8 * 60 * 60;
        }
        // POST: Websites/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "id,url,title,desc,categoryid,faviconurl")] website website)
        {
            website.createat = GetPHPTimeStamp();
            website.updateat = null;
            website.state = 0;

            website.faviconurl = DownloadFavicon(website.url);
            if (ModelState.IsValid)
            {
                if (db.websites.Any(w => w.url == website.url))
                {
                    throw new Exception($"{website.url} 已存在");
                }
                db.websites.Add(website);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.categoryid = new SelectList(db.categories, "id", "name", website.categoryid);
            return View(website);
        }

        private string DownloadFavicon(string url)
        {
            if (!url.StartsWith("http"))
            {
                return url;
            }
            Uri uri = new Uri(url);
            var favicon_url = uri.Scheme + "://" + uri.Host + "/favicon.ico";

            try
            {
                WebClient wc = new WebClient();
                var dir = AppDomain.CurrentDomain.BaseDirectory + "favicon";
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                var fileName = "favicon\\" + uri.Host + ".favicon.ico";
                wc.DownloadFile(favicon_url, AppDomain.CurrentDomain.BaseDirectory + fileName);
                return fileName;
            }
            catch (Exception ex)
            {
            }
            return favicon_url;
        }

        // GET: Websites/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            website website = db.websites.Find(id);
            if (website == null)
            {
                return HttpNotFound();
            }
            ViewBag.categoryid = new SelectList(db.categories, "id", "name", website.categoryid);
            return View(website);
        }

        // POST: Websites/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "id,url,title,desc,categoryid")] website website)
        {
            if (ModelState.IsValid)
            {
                website website_db = db.websites.Find(website.id);
                website_db.url = website.url;
                website_db.title = website.title;
                website_db.desc = website.desc;
                website_db.categoryid = website.categoryid;
                website_db.updateat = GetPHPTimeStamp();
                website_db.faviconurl = DownloadFavicon(website.url);
                db.Entry(website_db).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.categoryid = new SelectList(db.categories, "id", "name", website.categoryid);
            return View(website);
        }

        // GET: Websites/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            website website = db.websites.Find(id);
            if (website == null)
            {
                return HttpNotFound();
            }
            return View(website);
        }

        // POST: Websites/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            website website = db.websites.Find(id);
            db.websites.Remove(website);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
